#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<cstdio>
#include<vector>
#include<string>
std::vector<int> data;
std::string space=" ";
enum{
  OK=1,
  OPEN_FILE_ERROR=1
};
int data_save()
{
  std::string name=std::to_string(time(nullptr));
  name+=".backup";
  FILE*fl=fopen(name.c_str(),"w");
  if(fl==nullptr) return OPEN_FILE_ERROR;
  
  std::string data_name;
  for(auto&e:data)
  {
    data_name+=std::to_string(e);
    data_name+=space;
  }
  fputs(data_name.c_str(),fl);
  fclose(fl);
  return OK;
}



void save()
{
  int status=0;
  pid_t id=fork();
  if(id==0)//子进程
  {
    int code=data_save();
    exit(code);
  }
  
    int code=WEXITSTATUS(status);  
    pid_t rid=waitpid(id,&status,0);
    if(rid>0)
    {
      if(code==0)
      printf("备份成功，exit status:%d\n",code);
   else printf("备份失败，exit status:%d\n",code);
    }

}
int main()
{
  int cnt=1;
  while(true)
  {
    data.push_back(cnt++);
    sleep(1);
    if(cnt%10==0)
    {
      save();
    }
  }
  return 0;
}
